package com.frxuexi.base.mvvm

import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.ViewDataBinding
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import java.lang.reflect.ParameterizedType

abstract class BaseFragment<VDB:ViewDataBinding,VM:BaseViewModel>:Fragment (){
    private val type by lazy { (javaClass.genericSuperclass as ParameterizedType).actualTypeArguments }

    protected val vm:VM by lazy {
        val clazz = type[1] as Class<VM>
        ViewModelProvider(requireActivity())[clazz]
    }

    protected val binding by lazy {
        val clazz = type[0] as Class<VDB>
        val method = clazz.getMethod("inflate", LayoutInflater::class.java)
        method.invoke(null,layoutInflater) as VDB
    }

    fun onError(t:Throwable){
        Log.i("===",t.message.toString())
        t.printStackTrace()
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        vm.onFailed.observe(requireActivity(),::onError)
        initView()
        initData()
        return binding.root
    }

    abstract fun initData()

    abstract fun initView()
}